package com.mulanweb.api.module.controller.admin;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.mulanweb.api.module.controller.BaseController;
import com.mulanweb.api.module.model.*;
import com.mulanweb.api.module.model.Collection;
import com.mulanweb.db.common.SQLGenerateHelper;
import com.mulanweb.validator.annotation.ValidateForm;

import java.util.*;

/**
 * Created by Administrator on 2016/11/8 0008.
 */
public class TicketController extends BaseController {

    @ValidateForm
    public void save() {
        Long sellerId = getParaToLong("sellerId");
        String title = getPara("title");
        String titleEn = getPara("titleEn");
        String description = getPara("description");
        Long cityId = getParaToLong("cityId");
        Integer typeId = getParaToInt("typeId");
        Float price = Float.parseFloat(getPara("price"));
        Float oldPrice = Float.parseFloat(getPara("oldPrice"));
        Float oldNzdPrice = Float.parseFloat(getPara("oldNzdPrice"));
        Float nzdPrice = Float.parseFloat(getPara("nzdPrice"));
        Integer total = getParaToInt("total");

        Integer adminId = getSessionAttr("adminId");
        if(adminId == null){
            returnFailureJson();
            //todo 返回到提示未登录界面
            return;
        }

        Ticket ticket = new Ticket();
        ticket.setSellerId(sellerId);
        ticket.setTitle(title);
        ticket.setTitleEn(titleEn);
        ticket.setDescription(description);

        ticket.setCpTd(getPara("cpTd"));
        ticket.setXcAp(getPara("xcAp"));
        ticket.setFySm(getPara("fySm"));
        ticket.setYdXz(getPara("ydXz"));
        ticket.setZySx(getPara("zySx"));
        ticket.setTgGz(getPara("tgGz"));

        ticket.setOldPrice(oldPrice);
        ticket.setOldNzdPrice(oldNzdPrice);
        ticket.setTypeId(typeId);
        ticket.setPrice(price);
        ticket.setBasicCommodity(1);//默认为基本商品
        ticket.setNzdPrice(nzdPrice);
        ticket.setTotal(total);
        ticket.setSurplusTotal(total);
        ticket.setUnitId(2);//默认单位为：元/张
        ticket.setCreateTime(new Date());
        if (ticket.getTypeId() == 1) {
            ticket.setScenicSpotId(cityId);
        } else {
            ticket.setCityId(cityId);
        }
        Seller seller = Seller.dao.findById(sellerId);
        if (seller != null) {
            if (ticket.getTypeId() == 1) {
                ScenicSpot scenicSpot = ScenicSpot.dao.findById(cityId);
                if (scenicSpot != null) {
                    ticket.setCityId(scenicSpot.getCityId());
                    if (ticket.save()) {
                        OperationHistory operationHistory = new OperationHistory();
                        //增加一条数据
                        operationHistory.setTypeId(30L);
                        operationHistory.setTargetId(ticket.getId());
                        operationHistory.setTableName("ticket");
                        operationHistory.setAdminId(adminId);
                        operationHistory.setCreateTime(new Date());
                        operationHistory.save();
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("ReturnCode", 1);
                        map.put("Data", ticket);
                        returnSuccessJson(map);
                    } else {
                        returnFailureJson();
                    }
                } else {
                    returnJson(0, "景点不存在");
                }
            } else {
                if (ticket.save()) {
                    OperationHistory operationHistory = new OperationHistory();
                    //增加一条数据
                    operationHistory.setTypeId(30L);
                    operationHistory.setTargetId(ticket.getId());
                    operationHistory.setTableName("ticket");
                    operationHistory.setAdminId(adminId);
                    operationHistory.setCreateTime(new Date());
                    operationHistory.save();
                    returnSuccessJson();
                } else {
                    returnFailureJson();
                }
            }
        } else {
            returnJson(0, "商家不存在");
        }
    }

    @ValidateForm
    public void search() {
        SQLGenerateHelper helper = new SQLGenerateHelper("ticket", "create_time desc");
        helper.addEqualsCondition("type_id", getParaToInt("typeId"));
        helper.addLikeCondition("title", getPara("title"));
        helper.addEqualsCondition("id",getPara("ticketId"));
        helper.addEqualsCondition("scenic_spot_id", getParaToLong("spotId"));
        String sellerName = getPara("sellerName");
        List<Long> sellerIds = new ArrayList<>();
        if (sellerName != null) {
            List<Seller> sellers = Seller.dao.find("SELECT * FROM seller WHERE seller_name LIKE ?", "%" + sellerName + "%");
            for (Seller seller : sellers) {
                sellerIds.add(seller.getId());
            }
        }
        helper.addInConditionToLong("seller_id", sellerIds);
        helper.addIsNullCondition("delete_time");
        Page<Ticket> page = Ticket.dao.paginate(getPageNumber(), getPageSize(), helper.getSqlSelect(), helper.getSqlExceptSelect(), helper.getQueryParas());
        returnPageModelJson(page);
    }

    @ValidateForm
    public void getDetail() {
        Integer ticketId = getParaToInt("targetId");
        Ticket ticket = Ticket.dao.findById(ticketId);
        if (StrKit.notNull(ticket)) {
            Seller seller = Seller.dao.findById(ticket.getSellerId());
            AllType allType = AllType.dao.findById(seller.getCategoryId());
            City city = City.dao.findById(ticket.getCityId());
            ScenicSpot scenicSpot = ScenicSpot.dao.findById(ticket.getScenicSpotId());
            List<Collection> collections = Collection.dao.find("SELECT * FROM collection WHERE type_id=23 AND target_id=?", ticket.getId());
            List<ContentEvaluate> evaluates = ContentEvaluate.dao.find("SELECT * FROM content_evaluate WHERE type_id=23 AND target_id=?", ticket.getId());
            List<Photo> photos = Photo.dao.find("SELECT * FROM photo WHERE type_id in (13,14) AND target_id=? ORDER BY type_id DESC", ticket.getId());
            List<String> photoPaths = new ArrayList<String>(photos.size());
            for (Photo pp : photos) {
                photoPaths.add(pp.getPath());
            }
            Map<String, Object> map = new HashMap<String, Object>();
            Map<String, Object> target = new HashMap<String, Object>();
            target.put("sellerName", seller.getSellerName());
            target.put("sellerCategory", allType.getName());
            target.put("score", ticket.countScore());
            target.put("collectionNumber", collections.size());
            target.put("evaluateNumber", evaluates.size());
            target.put("cityName", city != null ? city : City.dao.findById(scenicSpot.getCityId()).getNameCn());
            target.put("scenicSpotName", scenicSpot.getScenicName());
            target.put("scenicSpotLocation", scenicSpot.getPosition());
            target.put("price", ticket.getPrice());
            target.put("oldNzdPrice", ticket.getOldNzdPrice());
            target.put("nzdPrice", ticket.getNzdPrice());
            target.put("titleEn", ticket.getTitleEn());
            target.put("oldPrice", ticket.getOldPrice());
            target.put("description", ticket.getDesc());
            target.put("title", ticket.getTitle());
            target.put("photos", photoPaths);

            target.put("cpTd", ticket.getCpTd());
            target.put("xcAp", ticket.getXcAp());
            target.put("fySm", ticket.getFySm());
            target.put("ydXz", ticket.getYdXz());
            target.put("zySx", ticket.getZySx());
            target.put("tgGz", ticket.getTgGz());

            map.put("ReturnCode", 1);
            map.put("ReturnStr", "操作成功");
            map.put("target", target);
            renderJson(map);
        } else {
            returnFailureJson();
        }
    }

    @ValidateForm
    public void delete() {
        Integer ticketId = getParaToInt("targetId");
        Ticket ticket = Ticket.dao.findById(ticketId);
        Integer adminId = getSessionAttr("adminId");
        if(adminId == null){
            returnFailureJson();
            //todo 返回到提示未登录界面
            return;
        }
        if (ticket != null) {
            ticket.setDeleteTime(new Date());
            if (ticket.update()) {
                OperationHistory operationHistory = new OperationHistory();
                //删除一条数据
                operationHistory.setTypeId(28L);
                operationHistory.setTargetId(ticket.getId());
                operationHistory.setTableName("ticket");
                operationHistory.setAdminId(adminId);
                operationHistory.setCreateTime(new Date());
                operationHistory.save();
                HotCommodity hotCommodity = HotCommodity.dao.findFirst("SELECT * FROM hot_commodity WHERE type_id = 23 AND target_id=?", ticket.getId());
                if (hotCommodity != null) {
                    hotCommodity.delete();
                }
                returnSuccessJson();
            } else {
                returnFailureJson();
            }
        } else {
            returnJson(0, "对象不存在");
        }
    }

    @ValidateForm
    public void update() {
        String title = getPara("title");
        String titleEn = getPara("titleEn");
        String description = getPara("description");
        Float price = Float.parseFloat(getPara("price"));
        Float nzdPrice = Float.parseFloat(getPara("nzdPrice"));
        Float oldNzdPrice = Float.parseFloat(getPara("oldNzdPrice"));
        Float oldPrice = Float.parseFloat(getPara("oldPrice"));
        Integer adminId = super.getSessionAttr("adminId");
        if(adminId == null){
            returnFailureJson();
            //todo 返回到提示未登录界面
            return;
        }

        Ticket ticket = Ticket.dao.findById(getParaToInt("ticketId"));
        ticket.setTitle(title);
        ticket.setTitleEn(titleEn);
        ticket.setDescription(description);
        ticket.setPrice(price);
        ticket.setNzdPrice(nzdPrice);
        ticket.setOldNzdPrice(oldNzdPrice);
        ticket.setOldPrice(oldPrice);

        ticket.setCpTd(getPara("cpTd"));
        ticket.setXcAp(getPara("xcAp"));
        ticket.setFySm(getPara("fySm"));
        ticket.setYdXz(getPara("ydXz"));
        ticket.setZySx(getPara("zySx"));
        ticket.setTgGz(getPara("tgGz"));
        if (ticket.update()) {
            OperationHistory operationHistory = new OperationHistory();
            //更新一条数据
            operationHistory.setTypeId(29L);
            operationHistory.setTargetId(ticket.getId());
            operationHistory.setTableName("ticket");
            operationHistory.setAdminId(adminId);
            operationHistory.setCreateTime(new Date());
            operationHistory.save();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("ReturnCode", 1);
            map.put("Data", ticket);
            returnSuccessJson(map);
        } else {
            returnFailureJson();
        }
    }

    @ValidateForm
    public void basicCommodity() {
        Ticket ticket = Ticket.dao.findById(getParaToInt("targetId"));
        if (StrKit.notNull(ticket)) {
            if (ticket.getBasicCommodity() == 0) {
                ticket.setBasicCommodity(1);
            } else {
                ticket.setBasicCommodity(0);
            }
            returnSuccessJson(ticket.update());
        } else {
            returnFailureJson();
        }
    }
}
